/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.github.florent37.camerafragment.sample.slice;

import static ohos.security.SystemPermission.CAMERA;
import static ohos.security.SystemPermission.MICROPHONE;
import static ohos.security.SystemPermission.READ_USER_STORAGE;
import static ohos.security.SystemPermission.WRITE_USER_STORAGE;

import com.github.florent37.camerafragment.CameraFraction;
import com.github.florent37.camerafragment.CameraFractionApi;
import com.github.florent37.camerafragment.configuration.Configuration;
import com.github.florent37.camerafragment.internal.ui.BaseAnncaFraction;
import com.github.florent37.camerafragment.internal.utils.Toast;
import com.github.florent37.camerafragment.listeners.CameraFragmentControlsAdapter;
import com.github.florent37.camerafragment.listeners.CameraFragmentResultListener;
import com.github.florent37.camerafragment.listeners.CameraFragmentStateListener;
import com.github.florent37.camerafragment.listeners.CameraFragmentVideoRecordTextAdapter;
import com.github.florent37.camerafragment.sample.CameraFragmentAbility;
import com.github.florent37.camerafragment.sample.ResourceTable;
import com.github.florent37.camerafragment.sample.bean.RxBusEvent;
import com.github.florent37.camerafragment.sample.rxbus.RxBus;
import com.github.florent37.camerafragment.widgets.CameraPhotoView;
import com.github.florent37.camerafragment.widgets.CameraSettingsView;
import com.github.florent37.camerafragment.widgets.CameraSwitchView;
import com.github.florent37.camerafragment.widgets.FlashSwitchView;
import com.github.florent37.camerafragment.widgets.MediaActionSwitchView;
import com.github.florent37.camerafragment.widgets.RecordButton;

import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.fraction.Fraction;
import ohos.aafwk.ability.fraction.FractionManager;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.DependentLayout;
import ohos.agp.components.Text;
import ohos.bundle.IBundleManager;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * 相机操作布局页面
 *
 * @since 2021-04-09
 */
public class CameraFragmentAbilitySlice extends AbilitySlice implements Component.ClickedListener,
    CameraSwitchView.CameraSwitchViewListener {
    private static final String FRAGMENT_TAG = "camera";
    private static final int REQUEST_CAMERA_PERMISSIONS = 931;
    private Text recordDurationText;
    private Text recordSizeText;
    private Button addCameraButton;
    private DependentLayout cameraLayout;
    private CameraPhotoView recordButton;
    private RecordButton startRecordButton;
    private RecordButton stopRecordButton;
    private FlashSwitchView flashSwitchView;
    private CameraSwitchView cameraSwitchView;
    private CameraSettingsView cameraSettingsView;
    private MediaActionSwitchView mediaActionSwitchView;
    private long clickTime;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        recordSizeText = (Text) findComponentById(ResourceTable.Id_record_size_mb_text); // 寻找控件
        recordDurationText = (Text) findComponentById(ResourceTable.Id_record_duration_text);
        recordButton = (CameraPhotoView) findComponentById(ResourceTable.Id_record_button);
        startRecordButton = (RecordButton) findComponentById(ResourceTable.Id_start_record_button);
        stopRecordButton = (RecordButton) findComponentById(ResourceTable.Id_stop_record_button);
        cameraLayout = (DependentLayout) findComponentById(ResourceTable.Id_cameraLayout);
        addCameraButton = (Button) findComponentById(ResourceTable.Id_addCameraButton);
        flashSwitchView = (FlashSwitchView) findComponentById(ResourceTable.Id_flash_switch_view);
        cameraSwitchView = (CameraSwitchView) findComponentById(ResourceTable.Id_front_back_camera_switcher);
        cameraSettingsView = (CameraSettingsView) findComponentById(ResourceTable.Id_settings_view);
        mediaActionSwitchView = (MediaActionSwitchView) findComponentById(ResourceTable.Id_photo_video_camera_switcher);

        recordButton.setClickedListener(this);
        startRecordButton.setClickedListener(this);
        stopRecordButton.setClickedListener(this);
        addCameraButton.setClickedListener(this);
        flashSwitchView.setClickedListener(this);
        cameraSettingsView.setClickedListener(this);
        mediaActionSwitchView.setClickedListener(this);
        cameraSwitchView.setCameraSwitchListener(this);
    }

    /**
     * 按钮点击事件
     *
     * @param component
     */
    @Override
    public void onClick(Component component) {
        switch (component.getId()) {
            case ResourceTable.Id_record_button: // 拍照
            case ResourceTable.Id_start_record_button: // 录制
            case ResourceTable.Id_stop_record_button: // 停止录制
                takePhotoOrRecordVideo();
                break;
            case ResourceTable.Id_addCameraButton: // 申请权限
                requestPermissionsAndOpenCamera();
                break;
            case ResourceTable.Id_flash_switch_view:
                final CameraFractionApi cameraFractionFlashSwitch = getCameraFragment();
                if (cameraFractionFlashSwitch != null) {
                    cameraFractionFlashSwitch.toggleFlashMode();
                }
                break;
            case ResourceTable.Id_settings_view:
                final CameraFractionApi cameraFractionSetting = getCameraFragment();
                if (cameraFractionSetting != null) {
                    cameraFractionSetting.openSettingDialog();
                }
                break;
            case ResourceTable.Id_photo_video_camera_switcher:
                final CameraFractionApi cameraFractionPhotoVideo = getCameraFragment();
                if (cameraFractionPhotoVideo != null) {
                    cameraFractionPhotoVideo.switchActionPhotoVideo();
                }
                break;
            default:
                break;
        }
    }

    private void requestPermissionsAndOpenCamera() { // 请求权限并打开相机
        List<String> permissionsToRequest = new ArrayList<>();
        String[] permissions = new String[]{CAMERA, MICROPHONE, READ_USER_STORAGE, WRITE_USER_STORAGE};
        for (String permission : permissions) {
            if (verifyCallingPermission(permission) != IBundleManager.PERMISSION_GRANTED) {
                // 应用未被授予权限
                if (canRequestPermission(permission)) { // 是否可以申请弹框授权 如果可以就把权限添加到列表中
                    permissionsToRequest.add(permission);
                }
            }
        }
        if (!permissionsToRequest.isEmpty()) {
            RxBusEvent busData = new RxBusEvent(); // 发送事件
            busData.setAbility(this);
            RxBus.get(this).send(busData);
            requestPermissionsFromUser(permissions, REQUEST_CAMERA_PERMISSIONS); // 说明有权限没有申请
        } else {
            addCamera(); // 开启相机
        }
    }

    private void takePhotoOrRecordVideo() { // 开始拍照和录像
        final CameraFractionApi cameraFractionRecord = getCameraFragment();
        if (cameraFractionRecord != null) {
            cameraFractionRecord.takePhotoOrCaptureVideo(new CameraFragmentResultListener() {
                @Override
                public void onVideoRecorded(String filePath) {
                    Toast.show(getContext(), "onVideoRecorded " + filePath);
                }

                @Override
                public void onPhotoTaken(String filePath) {
                    Toast.show(getContext(), "onPhotoTaken " + filePath);
                }
            }, getExternalFilesDir("").getAbsolutePath(), null);
        }
    }

    /**
     * 打开相机
     */
    public void addCamera() {
        addCameraButton.setVisibility(Component.HIDE);
        cameraLayout.setVisibility(Component.VISIBLE);

        CameraFraction cameraFraction = CameraFraction.newInstance(new Configuration.Builder()
            .setCamera(Configuration.CAMERA_FACE_REAR).build());
        FractionManager fractionManager = ((CameraFragmentAbility) getAbility()).getFractionManager();
        fractionManager.startFractionScheduler()
            .add(ResourceTable.Id_content, cameraFraction, FRAGMENT_TAG)
            .submit();
        if (cameraFraction != null) {
            cameraFraction.setStateListener(new CameraFragmentState());

            cameraFraction.setControlsListener(new CameraFragmentCtrlAdapter());

            cameraFraction.setTextListener(new CameraFragmentVideoRecordText());
        }
    }

    private BaseAnncaFraction getCameraFragment() {
        FractionManager fractionManager = ((CameraFragmentAbility) getAbility()).getFractionManager();
        Optional<Fraction> fractionByTag = fractionManager.getFractionByTag(FRAGMENT_TAG);
        if (fractionByTag.isPresent()) {
            return (BaseAnncaFraction) fractionByTag.get();
        } else {
            return new BaseAnncaFraction();
        }
    }

    private void displayVideoRecordStateReady() { // 显示录制按钮样式
        startRecordButton.setVisibility(Component.VISIBLE);
        stopRecordButton.setVisibility(Component.HIDE);
        recordButton.setVisibility(Component.HIDE);
    }

    private void displayVideoRecordStateInProgress() { // 显示停止按钮样式
        stopRecordButton.setVisibility(Component.VISIBLE);
        recordButton.setVisibility(Component.HIDE);
        startRecordButton.setVisibility(Component.HIDE);
    }

    private void displayPhotoState() { // 显示拍照按钮样式
        recordButton.setVisibility(Component.VISIBLE);
        recordButton.setEnabled(true);
        startRecordButton.setVisibility(Component.HIDE);
        stopRecordButton.setVisibility(Component.HIDE);
    }

    @Override
    protected void onBackPressed() {
        super.onBackPressed();
        terminateAbility();
    }

    /**
     * 前置和后置图标切换回调
     */
    @Override
    public void setSwitchListener() {
        final CameraFractionApi cameraFractionFrontBack = getCameraFragment();
        if (cameraFractionFrontBack != null) {
            cameraFractionFrontBack.switchCameraTypeFrontBack();
        }
    }

    /**
     * 相机fragment状态回调
     *
     * @since 2021-04-10
     */

    private class CameraFragmentState implements CameraFragmentStateListener {
        @Override
        public void onCurrentCameraBack() {
            cameraSwitchView.displayBackCamera();
        }

        @Override
        public void onCurrentCameraFront() {
            cameraSwitchView.displayFrontCamera();
        }

        @Override
        public void onFlashAuto() {
            flashSwitchView.displayFlashAuto();
        }

        @Override
        public void onFlashOn() {
            flashSwitchView.displayFlashOn();
        }

        @Override
        public void onFlashOff() {
            flashSwitchView.displayFlashOff();
        }

        @Override
        public void onCameraSetupForPhoto() {
            mediaActionSwitchView.displayActionWillSwitchVideo();
            displayPhotoState(); // 显示拍照按钮样式
            flashSwitchView.setVisibility(Component.VISIBLE);
        }

        @Override
        public void onCameraSetupForVideo() {
            mediaActionSwitchView.displayActionWillSwitchPhoto();
            displayVideoRecordStateReady(); // 显示开始录制样式
            flashSwitchView.setVisibility(Component.HIDE);
        }

        @Override
        public void onRecordStateVideoReadyForRecord() {
            displayVideoRecordStateReady(); // 显示开始录制样式
        }

        @Override
        public void onRecordStateVideoInProgress() {
            displayVideoRecordStateInProgress(); // 显示停止录制样式
        }

        @Override
        public void onRecordStatePhoto() {
            displayPhotoState(); // 显示拍照按钮样式
        }

        @Override
        public void shouldRotateControls(int degrees) { // 设置旋转控制
            cameraSwitchView.setRotation(degrees);
            mediaActionSwitchView.setRotation(degrees);
            flashSwitchView.setRotation(degrees);
            recordDurationText.setRotation(degrees);
            recordSizeText.setRotation(degrees);
        }

        @Override
        public void onStartVideoRecord(File outputFile) {
        }

        @Override
        public void onStopVideoRecord() {
            recordSizeText.setVisibility(Component.HIDE);
            cameraSettingsView.setVisibility(Component.VISIBLE);
        }
    }

    /**
     * 相机页面控制
     *
     * @since 2021-04-10
     */
    private class CameraFragmentCtrlAdapter extends CameraFragmentControlsAdapter {
        @Override
        public void lockControls() {
            cameraSwitchView.setEnabled(false);
            recordButton.setEnabled(false);
            cameraSettingsView.setEnabled(false);
            flashSwitchView.setEnabled(false);
        }

        @Override
        public void unLockControls() {
            cameraSwitchView.setEnabled(true);
            recordButton.setEnabled(true);
            cameraSettingsView.setEnabled(true);
            flashSwitchView.setEnabled(true);
        }

        @Override
        public void allowCameraSwitching(boolean isAllow) {
            cameraSwitchView.setVisibility(isAllow ? Component.VISIBLE : Component.HIDE);
        }

        @Override
        public void allowRecord(boolean isAllow) {
            recordButton.setEnabled(isAllow);
        }

        @Override
        public void setMediaActionSwitchVisible(boolean isVisible) {
            mediaActionSwitchView.setVisibility(isVisible ? Component.VISIBLE : Component.INVISIBLE);
        }
    }

    /**
     * 录像的时间显示
     *
     * @since 2021-04-10
     */
    private class CameraFragmentVideoRecordText extends CameraFragmentVideoRecordTextAdapter {
        @Override
        public void setRecordSizeText(long size, String text) {
            recordSizeText.setText(text);
        }

        @Override
        public void setRecordSizeTextVisible(boolean isVisible) {
            recordSizeText.setVisibility(isVisible ? Component.VISIBLE : Component.HIDE);
        }

        @Override
        public void setRecordDurationText(String text) {
            recordDurationText.setText(text);
        }

        @Override
        public void setRecordDurationTextVisible(boolean isVisible) {
            recordDurationText.setVisibility(isVisible ? Component.VISIBLE : Component.HIDE);
        }
    }
}
